﻿using System;
using System.Data;
using System.Data.SqlClient;

namespace QQ2564874169.RelationalSql.Dapper
{
    public class MsSql : DapperSql
    {
        private static string CreateConnectString(string host, string database, string user, string pwd)
        {
            if (host.Contains(":"))
            {
                var items = host.Split(':');
                int port;
                if (items.Length != 2 || int.TryParse(items[1], out port) == false)
                {
                    throw new FormatException($"host格式不正确：{host}。");
                }
                host = host.Replace(":", ",");
            }
            return
                $"Data Source={host};Initial Catalog={database};Integrated Security=false;User ID={user};Password={pwd}";
        }

        public MsSql(string host, string database, string user, string pwd)
            : this(CreateConnectString(host, database, user, pwd))
        {

        }

        public MsSql(string connectString) : base(new SqlConnection(connectString))
        {

        }

        protected override SqlParamValue ToParamValue(object item)
        {
            var value = base.ToParamValue(item);
            if (value.Value is ulong)
            {
                long i;
                if (long.TryParse(value.Value.ToString(), out i))
                {
                    value.Value = i;
                }
                else
                {
                    throw new InvalidCastException("ulong强转long失败。");
                }
            }
            return value;
        }
    }
}
